import 'dart:io';
import 'pdf_generator.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:printing/printing.dart';
import 'package:pdf/pdf.dart';

class PdfGenerationPage extends StatefulWidget {
  const PdfGenerationPage({super.key});

  @override
  _PdfGenerationPageState createState() => _PdfGenerationPageState();
}

class _PdfGenerationPageState extends State<PdfGenerationPage> {
  File? _generatedPdf;

  Future<void> _generatePdf() async {
    try {
      final pdfFile = await PdfGenerator.generatePdf();
      setState(() {
        _generatedPdf = pdfFile;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('PDF 生成成功：${pdfFile.path}')),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('PDF 生成失败：$e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PDF 生成示例'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: _generatePdf,
              child: Text('生成 PDF'),
            ),
            if (_generatedPdf != null)
              ElevatedButton(
                onPressed: () async {
                  try {
                    await Printing.layoutPdf(
                      onLayout: (PdfPageFormat format) async =>
                          _generatedPdf!.readAsBytes(),
                    );
                  } catch (e) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('打印 PDF 失败：$e')),
                    );
                  }
                },
                child: Text('打印 PDF'),
              ),
          ],
        ),
      ),
    );
  }
}